import http from '../api/httpRequest.js'
import {TERMINAL_TYPE} from "../api/enums.js"

export default {

	state: {
		friends: [],
		activeFriend: null,
		timer: null,
		friendApplyCount: 0  // 添加好友申请未读计数
	},
	mutations: {
		setFriends(state, friends) {
			friends.forEach((f)=>{
				f.online = false;
				f.onlineWeb = false;
				f.onlineApp = false;
			})
			state.friends = friends;
		},
		updateFriend(state,friend){
			state.friends.forEach((f,index)=>{
				if(f.id==friend.id){
					// 拷贝属性
					let online = state.friends[index].online;
					Object.assign(state.friends[index], friend);
					state.friends[index].online =online;
				}
			})
		},
		activeFriend(state, idx) {
			state.activeFriend = state.friends[idx];
		},
		removeFriend(state, idx) {
			try {
				// 如果提供的是对象而不是索引，尝试在数组中查找该对象
				if (typeof idx === 'object' && idx !== null) {
					const friendId = idx.id;
					if (!friendId) {
						console.error('removeFriend: 提供的对象没有id属性');
						return;
					}
					
					idx = state.friends.findIndex(f => f.id === friendId);
					if (idx === -1) {
						console.warn(`removeFriend: 未找到ID为${friendId}的好友`);
						return; // 未找到对应的好友
					}
				}
				
				// 确保索引有效
				if (idx < 0 || idx >= state.friends.length) {
					console.error('removeFriend: 尝试删除无效的好友索引:', idx);
					return;
				}
				
				// 记录被删除的好友信息（用于调试）
				const friendToRemove = state.friends[idx];
				console.log(`正在删除好友: ${friendToRemove.nickName || '未知'} (ID: ${friendToRemove.id || '未知'})`);
				
				// 如果删除的是当前激活的好友，清空激活状态
				if (state.friends[idx] === state.activeFriend) {
					console.log('删除的是当前激活的好友，清空激活状态');
					state.activeFriend = null;
				}
				
				// 删除好友
				state.friends.splice(idx, 1);
				console.log('好友删除成功，当前好友数量:', state.friends.length);
			} catch (error) {
				console.error('removeFriend执行出错:', error);
			}
		},
		addFriend(state, friend) {
			state.friends.push(friend);
		},
		refreshOnlineStatus(state){
			let userIds = [];
			if(state.friends.length ==0){
				return; 
			}
			state.friends.forEach((f)=>{userIds.push(f.id)});
			http({
				url: '/user/terminal/online',
				method: 'get',
				params: {userIds: userIds.join(',')}
			}).then((onlineTerminals) => {
				this.commit("setOnlineStatus",onlineTerminals);
			})
			
			// 30s后重新拉取
			state.timer && clearTimeout(state.timer);
			state.timer = setTimeout(()=>{
				this.commit("refreshOnlineStatus");
			},30000)
		},
		setOnlineStatus(state,onlineTerminals){
			state.friends.forEach((f)=>{
				let userTerminal = onlineTerminals.find((o)=> f.id==o.userId);
				if(userTerminal){
					f.online = true;
					f.onlineWeb = userTerminal.terminals.indexOf(TERMINAL_TYPE.WEB)>=0
					f.onlineApp = userTerminal.terminals.indexOf(TERMINAL_TYPE.APP)>=0
				}else{
					f.online = false;
					f.onlineWeb = false;
					f.onlineApp = false;
				}
			});
			// 在线的在前面
			state.friends.sort((f1,f2)=>{
				if(f1.online&&!f2.online){
					return -1;
				}
				if(f2.online&&!f1.online){
					return 1;
				}
				return 0;
			});
		},
		incrementFriendApplyCount(state) {
			state.friendApplyCount++;
		},
		resetFriendApplyCount(state) {
			state.friendApplyCount = 0;
		},
		clear(state) {
			state.timer && clearTimeout(state.timer);
			state.friends = [];
			state.timer = null;
			state.activeFriend = [];
		}
	},
	actions: {
		loadFriend(context) {
			return new Promise((resolve, reject) => {
				http({
					url: '/friend/list',
					method: 'GET'
				}).then((friends) => {
					let ff = friends.filter(m => m.temporary=='N'); //过滤临时好友
					context.commit("setFriends", ff);
					context.commit("refreshOnlineStatus");
					resolve(ff);
				}).catch((error) => {
					console.error('加载好友列表失败:', error);
					reject(error);
				})
			});
		}
	}
}
